package cc.lucien.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/checkCode")
public class CheckCodeServlet extends HttpServlet {

    private Random random = new Random();   //随机数对象
    private int width = 80;     //宽度
    private int height = 30;    //高度
    private int fontSize = 18;  //字体大小
    private String str = "0123456789abcdefghi";

    /**
     * 生成随机字符串
     * @return
     */
    private String randomCode(int len){
        if (len < 4)
            len = 4;
        width = 5 + fontSize * len;
        String code = "";
        for (int i = 0; i < len; i++){
            code += str.charAt(random.nextInt(str.length()));
        }
        return code;
    }

    /**
     * 生成随机颜色的方法
     * @return
     */
    private Color randomColor(){
        int r = random.nextInt(256);
        int g = random.nextInt(256);
        int b = random.nextInt(256);
        return new Color(r, g, b);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.创建画板
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //2.创建画笔
        Graphics2D pen = (Graphics2D) bufferedImage.getGraphics();
        //3.生成随机内容
        String code = randomCode(4);
        req.getSession().getServletContext().setAttribute("checkCode", code);
        //4.绘制随机内容
        //  4.1设置绘制区域
        pen.fillRect(0,0,width,height);
        //  4.2设置字体
        pen.setFont(new Font("微软雅黑", Font.BOLD, fontSize));
        //  4.3按顺序逐个绘制字符
        for (int i = 0; i < code.length(); i++){
            pen.setColor(randomColor());
            //绘制字符
            pen.drawString(code.charAt(i)+"", 5+i*fontSize, (height+fontSize)/2);
        }
        //  4.5绘制噪音线
        for (int i = 0; i < 4; i++){
            //设置线条颜色
            pen.setColor(randomColor());
            //设置线条粗细
            pen.setStroke(new BasicStroke(1));
            pen.drawLine(random.nextInt(width/2),random.nextInt(height),
                    random.nextInt(width), random.nextInt(height));
        }
        //5.存为图片并发送
        ServletOutputStream out = resp.getOutputStream();
        ImageIO.write(bufferedImage, "png", out);
        out.flush();
        out.close();
    }
}
